<template>
	<view class="phxx-item-detail">
		<view class="content-box">
			<view class="bottom block-back">
				<view class="uni-form-item">
					<view class="title"><span style="color:red;">*</span>地址类型</view>
					<view class="uni-select-box">
					    <picker :disabled="isDisabled" @change="changeAdress" :value="itemList.siteType" mode="selector" :range="adressRange" range-key="text">
							<view class="uni-input">{{siteTypeName || ''}}</view>
					    </picker>
					    <uni-icons type="forward" size="20"></uni-icons>
					</view>
				</view>
				<view class="uni-form-item">
					<text class="title"><span style="color:red;">*</span>地址名称</text>
					<input class="uni-input" v-model="itemList.siteName"/>
				</view>
				<view class="uni-form-item">
					<view class="title"><span style="color:red;">*</span>省</view>
					<view class="uni-select-box">
					    <picker :disabled="isDisabled" @change="changeProvince" :value="itemList.province" mode="selector" :range="provinceLists" range-key="text">
							<view class="uni-input">{{itemList.provinceName || ''}}</view>
					    </picker>
					    <uni-icons type="forward" size="20"></uni-icons>
					</view>
				</view>
				<view class="uni-form-item">
					<view class="title"><span style="color:red;">*</span>市</view>
					<view class="uni-select-box">
					    <picker :disabled="isDisabled" @change="changeCity" :value="itemList.city" mode="selector" :range="cityLists" range-key="text">
							<view class="uni-input">{{itemList.cityName || ''}}</view>
					    </picker>
					    <uni-icons type="forward" size="20"></uni-icons>
					</view>
				</view>
				<view class="uni-form-item">
					<view class="title"><span style="color:red;">*</span>区县</view>
					<view class="uni-select-box">
					    <picker :disabled="isDisabled" @change="changeCuontry" :value="itemList.county" mode="selector" :range="cuontryLists" range-key="text">
							<view class="uni-input">{{itemList.countyName || ''}}</view>
					    </picker>
					    <uni-icons type="forward" size="20"></uni-icons>
					</view>
				</view>
				<view class="uni-form-item">
					<view class="title"><span style="color:red;">*</span>街道</view>
					<view class="uni-select-box">
					    <picker :disabled="isDisabled" @change="changeTown" :value="itemList.town" mode="selector" :range="townLists" range-key="text">
							<view class="uni-input">{{itemList.townName || ''}}</view>
					    </picker>
					    <uni-icons type="forward" size="20"></uni-icons>
					</view>
				</view>
				<view class="uni-form-item">
					<text class="title"><span style="color:red;">*</span>详细地址</text>
					<input class="uni-input" v-model="itemList.address"/>
				</view>
				
			</view>
			<view class="btns">
				<button type="primary" @click="handleClick">确认</button>
			</view>
		</view>	
	</view>
</template>

<script>
import { toast } from '@/utils/common';
import { getAreaTrees,createOne,getOne,updateOne,getAreaTreesBycode } from '@/api/address.js';
export default {
	driverName: 'resetPwd',
	props: {
	},
	data() {
		return {
			siteTypeName: '',
			searchData: {
				lat: '',
				lon: ''
			},
			address:'',
			adressRange: [{
					"value": 1,
					"text": "装货地",
				},
				{
					"value": 2,
					"text": "卸货地"
				}
			],
			itemList: {
				id: undefined,
				siteType: undefined,
				siteName: undefined,
				province: undefined,
				provinceName: undefined,
				city: undefined,
				cityName: undefined,
				county: undefined,
				countyName: undefined,
				town: undefined,
				townName: undefined,
				address: undefined,
				lonLat: undefined
			},
			totalSeconds: 60,
			provinceLists: [],
			cityLists: [],
			cuontryLists: [],
			townLists: [],
			tempDatas: {},
			isEdit:false,
			fromMap: false,
			ifFirstEdit: true,
			isEditType: 'add'
		};
	},
	onLoad(options) {
		this.fromMap = false
		if(!!options){
			this.isEdit = true
			if(!!options.id){
				this.isEditType = "update"
				this.getDetail(options.id)
			}
			else this.isEdit = false
		}
		if(!this.isEdit){
			uni.setNavigationBarTitle({
				title: '添加'
			});
		}else{
			uni.setNavigationBarTitle({
				title: '编辑'
			});
		}
		this.getProvinces()
	},
	watch:{
		'itemList.province': function(newVal,oldVal){
			if(!this.isEdit){
				this.itemList.city = undefined
				this.itemList.county = undefined
				this.itemList.town = undefined
				this.itemList.cityName = undefined
				this.itemList.countyName = undefined
				this.itemList.townName = undefined
			}
			if(!!newVal) this.getCitys(newVal)
		},
		'itemList.city': function(newVal,oldVal){
			if(!this.isEdit){
				this.itemList.county = undefined
				this.itemList.town = undefined
				this.itemList.countyName = undefined
				this.itemList.townName = undefined
			}
			if(!!newVal) this.getCountys(newVal)
		},
		'itemList.county': function(newVal,oldVal){
			if(!this.isEdit){
				this.itemList.town = undefined
				this.itemList.townName = undefined
			}
			this.isEdit = false
			if(!!newVal) this.getTowns(newVal)
		}
	},
	methods: {
		async getDetail(id){
			let data = await getOne(id)
			let _ = this
			if(data.code == 0){
				_.tempDatas = data.data
				_.itemList.id = data.data.id
				_.itemList.siteName = data.data.siteName
				_.itemList.siteType = data.data.siteType
				
				if(_.adressRange.length > 0){
					_.adressRange.forEach(item=>{
						if(item.value == data.data.siteType) _.siteTypeName = item.text
					})
				}
				_.itemList.address = data.data.address
				_.itemList.province = data.data.province
				_.itemList.provinceName = data.data.provinceName
				_.itemList.city = data.data.city
				_.itemList.cityName = data.data.cityName
				
				_.itemList.county = data.data.county
				_.itemList.countyName = data.data.countyName
				_.itemList.town = data.data.town
				_.itemList.townName = data.data.townName
			}
		},
		async getProvinces(){
			let data = await getAreaTreesBycode(0)
			
			if(!!data){
				if(!!data.data && data.data.length > 0){
					this.provinceLists = []
					data.data.forEach(item=>{
						this.provinceLists.push({
							value: item.code,
							text: item.name
						})
					})
				}
			}
		},
		async getCitys(id){
			let data = await getAreaTreesBycode(id)
			if(!!data && data.data.length > 0){
				this.cityLists = []
				data.data.forEach(item=>{
					this.cityLists.push({
						value: item.code,
						text: item.name
					})
				})
				// if(this.isEdit) this.itemList.city = this.tempDatas.city
			}
		},
		async getCountys(id){
			let data = await getAreaTreesBycode(id)
			if(!!data && data.data.length > 0){
				this.cuontryLists = []
				data.data.forEach(item=>{
					this.cuontryLists.push({
						value: item.code,
						text: item.name
					})
				})
				// if(this.isEdit) this.itemList.county = this.tempDatas.county
			}
		},
		async getTowns(id){
			let data = await getAreaTreesBycode(id)
			if(!!data && data.data.length > 0){
				this.townLists = []
				data.data.forEach(item=>{
					this.townLists.push({
						value: item.code,
						text: item.name
					})
				})
				// if(this.isEdit) this.itemList.town = this.tempDatas.town
			}
		},
		changeProvince(e){
			this.ifFirstEdit = false
			if(this.provinceLists.length > 0){
				this.itemList.provinceName = this.provinceLists[e.detail.value].text
				this.itemList.province = this.provinceLists[e.detail.value].value
			}
			if(!this.isEdit){
				this.itemList.city = undefined
				this.itemList.county = undefined
				this.itemList.town = undefined
				this.itemList.cityName = undefined
				this.itemList.countyName = undefined
				this.itemList.townName = undefined
			}
			if(!!this.provinceLists[e.detail.value].value) this.getCitys(this.provinceLists[e.detail.value].value)
		},
		changeCity(e){
			this.ifFirstEdit = false
			this.itemList.city = e
			if(this.cityLists.length > 0){
				this.itemList.cityName = this.cityLists[e.detail.value].text
				this.itemList.city = this.cityLists[e.detail.value].value
			}
			if(!this.isEdit){
				this.itemList.county = undefined
				this.itemList.town = undefined
				this.itemList.countyName = undefined
				this.itemList.townName = undefined
			}
			if(!!this.cityLists[e.detail.value].value) this.getCountys(this.cityLists[e.detail.value].value)
		},
		changeCuontry(e){
			this.ifFirstEdit = false
			if(this.cuontryLists.length > 0){
				this.itemList.countyName = this.cuontryLists[e.detail.value].text
				this.itemList.county = this.cuontryLists[e.detail.value].value
			}
			if(!this.isEdit){
				this.itemList.town = undefined
				this.itemList.townName = undefined
			}
			this.isEdit = false
			if(!!this.cuontryLists[e.detail.value].value) this.getTowns(this.cuontryLists[e.detail.value].value)
		},
		changeTown(e){
			this.ifFirstEdit = false
			if(this.townLists.length > 0){
				this.itemList.townName = this.townLists[e.detail.value].text
				this.itemList.town = this.townLists[e.detail.value].value
			}
			if(!this.fromMap) this.itemList.address = this.itemList.provinceName + this.itemList.cityName + this.itemList.countyName + this.itemList.townName 
		},
		changeAdress(e){
			if(this.adressRange.length > 0){
				this.itemList.supplierName = this.adressRange[e.detail.value].text
				this.siteTypeName = this.adressRange[e.detail.value].text
				this.itemList.siteType = this.adressRange[e.detail.value].value
			}
		},
		chooseAdress(){
			let _this = this
			wx.chooseLocation({
				success: (res) => {
					console.log(res, '这是获取到的地理位置')
					this.itemList.province = undefined
					this.itemList.provinceName = undefined
					this.itemList.city = undefined
					this.itemList.county = undefined
					this.itemList.town = undefined
					this.itemList.cityName = undefined
					this.itemList.countyName = undefined
					this.itemList.townName = undefined
					this.itemList.address = res.address
					this.fromMap = true
				},
				fail: (err) => {
					console.log(err);
				}
			});
		},
		async handleClick() {
			let data = {}
			let _ = this
			if(!_.itemList.siteType){
				toast(`请选择装货地类型`);
				return
			}
			if(!_.itemList.siteName){
				toast(`地址名称不能为空`);
				return
			}
			if(!_.itemList.provinceName){
				toast(`省不能为空`);
				return
			}
			if(!_.itemList.cityName){
				toast(`市不能为空`);
				return
			}
			if(!_.itemList.countyName){
				toast(`区县不能为空`);
				return
			}
			if(!_.itemList.townName){
				toast(`街道不能为空`);
				return
			}
			if(!_.itemList.address){
				toast(`详细地址不能为空`);
				return
			}
			let msg = ""
			if(this.isEditType == 'update'){
				msg = "编辑"
				data = await updateOne(this.itemList)
			}else{
				msg = "添加"
				data = await createOne(this.itemList)
			}
			if(data.code == 0){
				uni.showToast({
					title: msg + '成功',
					icon: 'success'
				});
				uni.navigateBack({
					delta: 1
				});
			}else{
				uni.showToast({
					title: msg + '失败',
					icon: 'failed'
				});
			}
		},
		parseTime(time, pattern) {
			if (arguments.length === 0 || !time) {
				return null;
			}
			const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
			let date;
			if (typeof time === 'object') {
				date = time;
			} else {
				if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
					time = parseInt(time);
				} else if (typeof time === 'string') {
					time = time
						.replace(new RegExp(/-/gm), '/')
						.replace('T', ' ')
						.replace(new RegExp(/\.[\d]{3}/gm), '');
				}
				if (typeof time === 'number' && time.toString().length === 10) {
					time = time * 1000;
				}
				date = new Date(time);
			}
			const formatObj = {
				y: date.getFullYear(),
				m: date.getMonth() + 1,
				d: date.getDate(),
				h: date.getHours(),
				i: date.getMinutes(),
				s: date.getSeconds(),
				a: date.getDay()
			};
			const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
				let value = formatObj[key];
				// Note: getDay() returns 0 on Sunday
				if (key === 'a') {
					return ['日', '一', '二', '三', '四', '五', '六'][value];
				}
				if (result.length > 0 && value < 10) {
					value = '0' + value;
				}
				return value || 0;
			});
			return time_str;
		}
	}
};
</script>

<style lang="scss" scoped>
.phxx-item {
	width: 700rpx;
	padding: 10rpx 30rpx;
	box-sizing: border-box;
	margin: 20rpx auto 20rpx auto;
	border-radius: 20rpx;
	background: #fff;
	font-size: 26.66rpx;
	color: #000;
	.phxx-item-content {
		width: 644rpx;
		.bottom{
			padding: 10rpx 0 0 0;
			> .items{
				padding-bottom: 6rpx;
				display: flex;
				align-items: center;
				border-bottom: 1px solid #ccc;
				padding-top: 15px;
			}
			.btn{
				button{
					width: 100%;
					height: 40px!important;
					margin-top: 45px;
					line-height: 40px!important;
				}
			}
			.til {
				width: 150rpx;
				display: inline-block;
			}
			.val {
				margin-left: 30rpx;
				width: 75%;
				display: inline-block;
				border-radius: 5px;
				height: 30px;
			}
		}
	}
}
</style>
